//
//  ProgramaViewController.m
//  Atlantis
//
//  Created by 何恩营 on 14-12-17.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

// 栏目页面
#import "ProgramaViewController.h"
#import "Music.h"
#import "MusicCell.h"
#import "NetHandler.h"
#import "PlayViewController.h"

#import "UIScrollView+Extension.h"
#import "UIScrollView+MJRefresh.h"

@interface ProgramaViewController ()<UITableViewDataSource, UITableViewDelegate>

// 表视图
@property(nonatomic, retain) UITableView *tableView;
// 分段控件
@property(nonatomic, retain) UISegmentedControl *segmentedControl;
// 专辑数组
@property(nonatomic, retain) NSMutableArray *musicArr;
// 页数
@property(nonatomic, assign) NSInteger page;
//// 网络请求参数
//@property(nonatomic, retain) NSString *condition;

@end

@implementation ProgramaViewController


- (void)dealloc
{
    // 分段控件
    [_segmentedControl release];
    // 表视图
    [_tableView release];
    // 专辑数组
    [_musicArr release];
    // 类型
    [_type release];
    // 标题
    [_cateTitle release];
    [super dealloc];
}



// 下拉刷新, 上拉加载更多
- (void)setupRefresh
{
    //    NSLog(@"进入了setupRefresh");
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    //进入刷新状态(一进入程序就下拉刷新)
    [self.tableView headerBeginRefreshing];
    
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
}
#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    UIView *view = [[UIView alloc] initWithFrame:self.view.bounds];
    view.backgroundColor = [UIColor clearColor];
    [self.view addSubview:view];
    [view release];

    //1. 在这调用请求网络数据方法（刷新数据）
    self.page = 1;
    if (self.segmentedControl.selectedSegmentIndex == 0) {
        [self handleDataWithStr:@"daily"];
    } else if (self.segmentedControl.selectedSegmentIndex == 1) {
        [self handleDataWithStr:@"hot"];
    } else {
        [self handleDataWithStr:@"favorite"];
    }
    //2. 2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        //[self.tableView reloadData];
        [view removeFromSuperview];
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.tableView headerEndRefreshing];
    });
}

//   进入加载状态
- (void)footerRereshing
{
    self.page += 1;
    //1. 拼接口等操作
    // 请求加载数据
    if (self.segmentedControl.selectedSegmentIndex == 0) {
        //[self handleDataWithStr:@"hot"];
        [self footerHandleWithStr:@"daily"];
        
    } else if (self.segmentedControl.selectedSegmentIndex == 1){
        [self footerHandleWithStr:@"hot"];
    } else {
        [self footerHandleWithStr:@"favorite"];
    }

    
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.tableView reloadData];
        [self.tableView footerEndRefreshing];
    });
    
}

// 数据处理
- (void)handleDataWithStr:(NSString *)str
{
    // 创建连接
    // 拼接网络地址
    NSString *path = [NSString stringWithFormat:@"http://mobile.ximalaya.com/m/explore_track_list?category_name=%@&condition=%@&device=iPhone&page=%ld&per_page=20&tag_name=", self.type, str, self.page];
    
    // 建立连接
    [NetHandler getDataWithURL:path completion:^(NSData *data) {
        // JSON解析
        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        // 创建专辑数组
        self.musicArr = [NSMutableArray array];
        // 获取数组
        NSArray *arr = [result objectForKey:@"list"];
        // 遍历数组
        for (NSDictionary *dic in arr) {
            // 创建对象
            Music *music = [[Music alloc] initWithDictionary:dic];
            // 赋值
            [self.musicArr addObject:music];
            // 内存管理
            [music release];
        }
        // 刷新
        [self.tableView reloadData];
        [self setupRefresh];
    }];
    
}

// 底端数据处理
- (void)footerHandleWithStr:(NSString *)str
{
    // 拼接网络地址
    NSString *path = [NSString stringWithFormat:@"http://mobile.ximalaya.com/m/explore_track_list?category_name=%@&condition=%@&device=iPhone&page=%ld&per_page=20&tag_name=", self.type, str, self.page];
    
    // 建立连接
    [NetHandler getDataWithURL:path completion:^(NSData *data) {
        // JSON解析
        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        // 获取数组
        NSArray *arr = [result objectForKey:@"list"];
        // 遍历数组
        for (NSDictionary *dic in arr) {
            // 创建对象
            Music *music = [[Music alloc] initWithDictionary:dic];
            // 赋值
            [self.musicArr addObject:music];
            // 内存管理
            [music release];
        }
    }];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.page = 1;
    [self handleDataWithStr:@"daily"];
    // Do any additional setup after loading the view.
    
    self.navigationItem.title = self.cateTitle;
    
    // 创建一个tableView
    self.tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
    // 视图加载
    [self.view addSubview:self.tableView];
    // 行高
    self.tableView.rowHeight = 120;
    // 分割线样式
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    // 指定代理人
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    // 内存管理
    [_tableView release];
    
    
    // 控件显示名字
    NSArray *array = [NSArray arrayWithObjects:@"最火", @"本周热门", @"最多赞", nil];
    // 创建分段控件
    self.segmentedControl = [[UISegmentedControl alloc] initWithItems:array];
    // 分段控件默认显示页面
    self.segmentedControl.selectedSegmentIndex = 0;
    // 分段控件的大小
    self.segmentedControl.frame = CGRectMake(20, 0, self.view.bounds.size.width - 40, 24);
    // 分段控件实现事件
    [self.segmentedControl addTarget:self action:@selector(segmentedControlClicked:) forControlEvents:UIControlEventValueChanged];
    // 将分段控件加载到tableView上
    //[self.tableView addSubview:self.segmentedControl];
    // 内存管理
    [_segmentedControl release];
    
    // 注册cell
    [self.tableView registerClass:[MusicCell class] forCellReuseIdentifier:@"reuse"];
    
    
    // 导航栏左侧返回按钮
    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"return.png"] style:UIBarButtonItemStyleDone target:self action:@selector(collectionAction:)] autorelease];
    
    
    
}


// 导航栏左侧返回按钮触发事件
- (void)collectionAction:(UINavigationBar *)bar
{
    //NSLog(@"返回前一页");
    // 推出前一页
    [self.navigationController popViewControllerAnimated:YES];
}


// cell的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.musicArr.count;
}

// cell的值
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 自定义cell
    MusicCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
    // cell赋值
    cell.music = [self.musicArr objectAtIndex:indexPath.row];
    
    return cell;
}

// 选中执行方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    
    // 创建播放视图
    PlayViewController *playVC = [PlayViewController sharePlayVC];
    
    // 获取对象值
    Music *music = [self.musicArr objectAtIndex:indexPath.row];
    
    // 判断播放是否同一对象
    if (![playVC.music.trackId isEqual:music.trackId]) {
        // 赋值
        playVC.musicArr = self.musicArr;
        // 当前音乐
        playVC.currentMusic = indexPath.row;
        // 播放音乐
        [playVC play];
    }
    // 推出界面
    [self.navigationController pushViewController:playVC animated:YES];
    
}

// section标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return [NSString stringWithFormat:@"section%ld", section];
}


// 自定义section
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSString *sectionTitle = [self tableView:tableView titleForHeaderInSection:section];
    if (sectionTitle == nil) {
        return nil;
    }
    // Create header view and add label as a subview
    UIView *sectionView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, tableView.bounds.size.height)] autorelease];
    [sectionView setBackgroundColor:[UIColor whiteColor]];
    // sectionView.userInteractionEnabled = YES;
    [sectionView addSubview:self.segmentedControl];
    
    return sectionView;
}

- (void)segmentedControlClicked:(UISegmentedControl *)seg
{
    // 利用switch来实现分段控件的不同下标的不同数据
    switch (seg.selectedSegmentIndex) {
        case 0:
            // 点击分段控件的下标显示"hot"的数据
            [self handleDataWithStr:@"daily"];
            break;
        case 1:
            // 点击分段控件的下标显示"recent"的数据
            [self handleDataWithStr:@"hot"];
            break;
        case 2:
            // 点击分段控件的下标显示"classic"的数据
            [self handleDataWithStr:@"favorite"];
            break;
        default:
            break;
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
